1178D - Prime Graph - CodeForces Solution


constructive algorithms greedy math number theory *1500

Please click on ads to support us..

Python Code:

def isprime(x):
    if x == 1:
        return False
    i = 2
    while i * i <= x:
        if x % i == 0:
            return False
        i += 1
    return True

def getrange(n):
    lower = n
    upper = n + n // 2
    return (lower, upper)

def main():
    
                                    
    n = int(input())
    if n <= 2:
        print(-1)
    
    lower, upper = getrange(n)
    p = -1
    for x in range(lower, upper + 1):
        if isprime(x):
            p = x
            break
    
    print(p)
    
    edges = []
    for i in range(n):
        edges.append((1 + i, 1 + ((i + 1) % n)))
    
    l, r = 0, n // 2
    while len(edges) < p:
        edges.append((1 + l, 1 + (r % n)))
        l += 1; r += 1
    multiLineArrayOfArraysPrint(edges)
    
    return

import sys
input=sys.stdin.buffer.readline  
def oneLineArrayPrint(arr):
    print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
    print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
    print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
 
def readIntArr():
    return [int(x) for x in input().split()]
 
def makeArr(defaultValFactory,dimensionArr):     dv=defaultValFactory;da=dimensionArr
    if len(da)==1:return [dv() for _ in range(da[0])]
    else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
 
def queryInteractive(a, b, c):
    print('? {} {} {}'.format(a, b, c))
    sys.stdout.flush()
    return int(input())
 
def answerInteractive(x1, x2):
    print('! {} {}'.format(x1, x2))
    sys.stdout.flush()
 
inf=float('inf')
 
from math import gcd,floor,ceil
import math
 
for _abc in range(1):
    main()

C++ Code:

#include<bits/stdc++.h>
#define fi first
#define se second
#define pq priority_queue
#define mp make_pair
#define str string
#define ll long long
#define ii pair<int, int>
#define pb push_back

using namespace std;

bool notprime[1010]; vector<int> primes;


void sieve() {
  for (int i=2; i<=1009; i++) {
    if (!notprime[i]) {
      primes.pb(i);
      for (int j=i+i; j<=1009; j+=i) notprime[j]=1;
    }
  }
}

void solve() {
  notprime[1]=1, notprime[0]=1;
  sieve();
  int n;
  cin >> n;
  vector<ii> ans;
  for (int i=1; i<=n; i++) {
    int nxt=(i==n)? 1:i+1;
    ans.pb(mp(i, nxt));
  }  
  bool possible=0;
  //cout << ans.size() << " is" << ((notprime[ans.size()])? " not ":" ") << "prime\n";
  if (n==2) possible=0;
  else if (!notprime[ans.size()]) possible=1;
  else {
    int l=0, r=primes.size(), sz=ans.size(), res=0;
    while (l<=r) {
      int mid=(l+r)/2;
      if (primes[mid] < sz) l=mid+1;
      else {
        res=primes[mid];
        r=mid-1;
      }
    }
    //cout << "Closest prime: " << res << "\n";
    int dif=res-sz, half=n/2;
    if (dif > half) possible=0; 
    else {
      possible=1;
      for (int i=1; i<=dif; i++) {
        int nxt=half+i;
        //cout << i << " " << nxt << "\n";
        ans.pb(mp(i, nxt));
      }
    }
  }
  
  if (possible) {
    cout << ans.size() << "\n";
    for (int i=0; i<ans.size(); i++) cout << ans[i].fi << " " << ans[i].se << "\n";
  }
  else cout << -1 << "\n";
}

int main() {
  ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
  solve();
  return 0;
}


Comments

Submit
0 Comments
More Questions

779. K-th Symbol in Grammar
701. Insert into a Binary Search Tree
429. N-ary Tree Level Order Traversal
739. Daily Temperatures
647. Palindromic Substrings
583. Delete Operation for Two Strings
518. Coin Change 2
516. Longest Palindromic Subsequence
468. Validate IP Address
450. Delete Node in a BST
445. Add Two Numbers II
442. Find All Duplicates in an Array
437. Path Sum III
436. Find Right Interval
435. Non-overlapping Intervals
406. Queue Reconstruction by Height
380. Insert Delete GetRandom O(1)
332. Reconstruct Itinerary
368. Largest Divisible Subset
377. Combination Sum IV
322. Coin Change
307. Range Sum Query - Mutable
287. Find the Duplicate Number
279. Perfect Squares
275. H-Index II
274. H-Index
260. Single Number III
240. Search a 2D Matrix II
238. Product of Array Except Self
229. Majority Element II